package com.polaris.live.ui.party.fragment.game

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.polaris.live.R
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentPartyGameSpectatorBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.dialog.SendFreeGiftSelectDialog
import com.polaris.live.dialog_fragment.MusicPopup
import com.polaris.live.dialog_fragment.RoomInvitationFragmentDialog
import com.polaris.live.dialog_fragment.magiclamp.MagicLampPopup
import com.polaris.live.im.manager.ImLiveManager
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.im.manager.RouterControlManager
import com.polaris.live.im.sfs.LIVE_CHANGED_GAME_REWARD
import com.polaris.live.im.sfs.LIVE_GIFT_LIST
import com.polaris.live.im.sfs.LIVE_INVITE_SITE
import com.polaris.live.im.sfs.LIVE_KICK_ROOM
import com.polaris.live.im.sfs.LIVE_MAGIC_LAMP_90
import com.polaris.live.im.sfs.LIVE_MAGIC_LAMP_OPEN
import com.polaris.live.im.sfs.LIVE_PARTY_EMOJI
import com.polaris.live.im.sfs.LIVE_PUBLIC_SCREEN
import com.polaris.live.im.sfs.LIVE_RELOAD_GAME
import com.polaris.live.im.sfs.LIVE_SEND_GIFT
import com.polaris.live.im.sfs.LIVE_WARN_MESSAGE
import com.polaris.live.im.sfs.LUCKY_BACKPACK_GIFT
import com.polaris.live.im.sfs.NEW_COUPLES_FREE_GIFTS
import com.polaris.live.im.sfs.bean.live.LivePublicScreenMessage
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.im.sfs.bean.live.SendLiveCloseMessage
import com.polaris.live.im.sfs.bean.live.SendLiveFloatingMessage
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.ext.LiveEnterBean
import com.polaris.live.im.sfs.bean.live.ext.MessageUserExtBean
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.im.sfs.bean.live.payload.GiftListPayloadBean
import com.polaris.live.im.sfs.bean.live.payload.InviteGiftPayloadBean
import com.polaris.live.im.sfs.bean.live.toUserBasic
import com.polaris.live.im.sfs.core.SmartFoxManager
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.core.bean.getRoomId
import com.polaris.live.im.utils.SmartFoxUtils.parseVariables
import com.polaris.live.interface_bag.XpopupCallBackImpl
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.popup.ContributionListPopup
import com.polaris.live.popup.GameListPopup
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.MagicLampWinRewardPopup
import com.polaris.live.popup.VipBarrageWhatPopup
import com.polaris.live.popup.party.InteractionEmojiPopup
import com.polaris.live.popup.party.InvitingSeatNoticePopup
import com.polaris.live.popup.party.LivePartyGameDrawerPopup
import com.polaris.live.popup.party.RoomInfoSpectatorPopup
import com.polaris.live.popup.party.RoomManagementPopup
import com.polaris.live.popup.party.SeatSettingPopup
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.back_resp.GiftBean
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.back_resp.LiveEmojiResp
import com.polaris.live.resp.back_resp.PartyGameSettlementResp
import com.polaris.live.resp.back_resp.toDisplayUserBean
import com.polaris.live.resp.back_resp.toUserBasicVo
import com.polaris.live.resp.bean.MagicLampCountDownBean
import com.polaris.live.resp.go_resp.SendGiftBean
import com.polaris.live.translation.R.string
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.live.bean.LiveInitInfo
import com.polaris.live.ui.live.proxy.LivePublicProxy
import com.polaris.live.ui.live.proxy.gift.EntryScreenAnimationProxy
import com.polaris.live.ui.live.proxy.gift.GiftAnimationProxy
import com.polaris.live.ui.live.widget.LiveFloatView
import com.polaris.live.ui.live.widget.listener.OnSendPartyMessageListener
import com.polaris.live.ui.message.fragment.MessageSessionFragment
import com.polaris.live.ui.message.fragment.dialog.MessageSessionDialogFragment
import com.polaris.live.ui.message.fragment.dialog.MessageSingleDialogFragment
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.ui.party.fragment.base.BasePartySpectatorFragment
import com.polaris.live.ui.party.listener.GamePlayListener
import com.polaris.live.ui.party.utils.GiftDialogProxy
import com.polaris.live.ui.party.utils.GiftGivingAnimationProxy
import com.polaris.live.ui.party.widget.PartyBottomView
import com.polaris.live.ui.party.widget.seat.SeatBeanUtil
import com.polaris.live.ui.party.widget.seat.bean.SeatBean
import com.polaris.live.ui.party.widget.seat.listener.PartySeatListener
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.TaskRedListener
import com.polaris.live.utils.TaskRedProxy
import com.polaris.live.utils.XPopupUtils
import com.polaris.live.utils.fragment.attachFragmentByTag
import com.polaris.live.utils.fragment.showNewDialogFragment
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.zego.LiveEngineManage
import com.polaris.live.utils.zego.core.ForwardGameEventHandlerListener
import com.polaris.live.utils.zego.media.MediaProxy
import com.polaris.live.viewmodel.party.game.PartyGameSpectatorFragmentModel
import im.zego.minigameengine.IZegoGameEngineHandler
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import sfs2x.client.core.SFSEvent
import sfs2x.client.entities.variables.RoomVariable

/**
 * 游戏语聊房
 *
 * @author Created by 天晴 on 2024/3/14 11:41
 * @since 1.0.0
 */
class PartyGameSpectatorFragment :
    BasePartySpectatorFragment<PartyGameSpectatorFragmentModel, FragmentPartyGameSpectatorBinding>(),
    GamePlayListener,
    ForwardGameEventHandlerListener {

    private var mLiveInfo: LiveRoomInfo? = null
    private var mGameMode: Boolean = false //是否在游戏模式
    private var mInSeat: Boolean = false //是否在游戏位
    private var mIsMatchCome: Boolean? = null//是从匹配过来的
    private var mSoundStatus: Boolean? = null//外部传递过来的麦克风状态
    private var mIsInitLiveInfo = false//

    //被禁言的人
    private val mBanMessageUser = mutableListOf<Long>()

    //房管
    private val mAdministrators = mutableListOf<Long>()

    private var mEmojiList: List<LiveEmojiResp>? = null

    private val mEntryScreenAnimationProxy by lazy {
        EntryScreenAnimationProxy(
            requireActivity(),
            mBinding.entryFloatingScreen,
            mBinding.entryScreen,
            viewLifecycleOwner
        )
    }

    //礼物列表消息  延迟后添加快捷礼物列表
    private var mGiftJob: Job? = null

    //礼物代理
    private var mGiftProxy: GiftAnimationProxy? = null

    //礼物轮盘代理
    private val mGiftDialogProxy by lazy {
        mLiveInfo?.let { da ->
            GiftDialogProxy(requireContext(), mViewModel, da, mBinding.icRun, true)
                .apply {
                    setOnUserProfileClickListener {//礼物轮盘点击查看礼物
                        showPartyUserProfilePopup(it, true)
                    }
                }
        }
    }

    private val mSessionFragment by lazy { MessageSessionDialogFragment() }

    private var mGamePlayFragment: GamePlayFragment? = null
    private var mBaiShunGamePlayFragment: BaiShunGamePlayFragment? = null

    private val mLivePublicProxy by lazy {
        LivePublicProxy(requireContext(), mViewModel)
    }

    private val mLivePartyGameDrawerPopup: LivePartyGameDrawerPopup by lazy {
        LivePartyGameDrawerPopup(
            requireActivity(),
            onToLive = {
                mLivePartyGameDrawerPopup.dismiss()
                nextData(it)
            }, onToParty = {
                mLivePartyGameDrawerPopup.dismiss()
                GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                    mViewModel.getPartyRoom()
                })
            }
        )
    }
    private val mGiftGivingAnimationProxy by lazy {
        GiftGivingAnimationProxy(mViewModel, this)
    }

    /**
     * 底部控制
     */
    private val mBottomBuilder by lazy {
        PartyBottomView.Builder()
            .setShowMessageButton(true)
            .setShowSendrButton(true)
            .setShowGiftButton(true)
            .setShowEmojiButton(false)
            .setShowSettingButton(true)
            .setShowGameButton(!GameUtils.getLiveCacheGameList().isNullOrEmpty())
            .setFreeGiftSourceType(AppConst.BackpackGiftComming.PARTY_GAME)
            .setEmojiClickBack {
                showInteractionEmojiPopup()
            }
            .setMessageClickBack {
                showChatMessage()
            }
            .setSendrClickBack {
                mEditView?.showKeyboard()
            }
            .setGameClickBack {
                showGameList()
            }
            .setMikeStateBack { //开关音频
                mLiveInfo?.let { li ->
                    mViewModel.siteMicSwitch(li.userId, it == 1)
                }
            }
            .setGiftClickBack {
                mGiftDialogProxy?.showGiftPopup(seatList = mBinding.partySeat.getSeatData())
            }
            .setSettingClickBack {
                showRoomManagementPopup()
            }
            .setFreeGiftClickBack { gift ->
                val seatData = mBinding.partySeat.getSeatData()
                if (CollectionUtils.isNotEmpty(seatData)) {
                    //如果麦位上只有自己
                    if (seatData.size == 1 && mBinding.partySeat.getMeSeatBean() != null) {
                        ToastGravity.showGravity(string.this_gift_dont_send_myself)
                    } else {
                        SendFreeGiftSelectDialog.show(requireContext(), seatData) {
                            mLiveInfo?.liveId?.let { liveId ->
                                mViewModel.sendFreeGift(it, gift, AppConst.BackpackGiftComming.PARTY_GAME, liveId)
                            }
                        }
                    }
                } else {//麦位没有人
                    ToastGravity.showGravity(string.seat_not_have_people)
                }
            }
    }

    override fun needShowViews() = listOf(
        mBinding.vMessage,
        mBinding.bottom.mBinding.sendr,
        mBinding.vHeader.mBinding.rvRecycler,
        mBinding.entryFloatingScreen,
        mBinding.widgetRoomBanner
    )

    override fun nextData(displayUserBean: DisplayUserBean) {
        if (displayUserBean.base.userId != mLiveInfo?.userId) {
            if (mBinding.partySeat.getMeSeatBean() != null || mInSeat) {
                ToastGravity.showGravity(string.sure_exit_party_tips)
            } else {
                mOnSpectatorFragmentListener?.nextData(displayUserBean)
            }

        }
    }

    override fun onMinimize() {
    }

    override fun roomType() = PARTY_GAME_ROOM

    override fun showGiftDialog() {
    }

    override fun switchUserRoom(anchorId: Long?, childRouter: String?) {
        withLoaded {
            if (anchorId != null && anchorId != mLiveInfo?.userId) {
                mViewModel.getGiftInfoUser(anchorId)
            } else {
                childRouter?.let { RouterUtils.routerGoto(it) }
            }
        }
    }

    override fun showRightPopup() {
        mLivePartyGameDrawerPopup.chageToParty()
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(false)
            .popupPosition(PopupPosition.Right)
            .setPopupCallback(object : XpopupCallBackImpl {
                override fun onDismiss(popupView: BasePopupView) {
                }
            })
            .asCustom(mLivePartyGameDrawerPopup)
            .show()
    }

    override fun onHideView(pd: Boolean) {
        mGiftProxy?.clearScreen(pd)
    }

    private fun getGameIsPlaying(): Boolean {
        return mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.isGamePlaying()
                }

                2 -> {
                    mGamePlayFragment?.isGamePlaying()
                }

                else -> {
                    false
                }
            }
        } ?: false

    }

    private fun gameResult(data: List<PartyGameSettlementResp>) {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.gameResult(data)
                }

                2 -> {
                    mGamePlayFragment?.gameResult(data)
                }

                else -> {}
            }
        }

    }

    private fun reloadGame() {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.reloadGame()
                }

                2 -> {
                    mGamePlayFragment?.reloadGame()
                }

                else -> {}
            }
        }
    }

    private fun loadGame(liveInfo: LiveRoomInfo) {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.loadGame(liveInfo)
                }

                2 -> {
                    mGamePlayFragment?.loadGame(liveInfo)
                }

                else -> {}
            }
        }

    }

    private fun exitFragmetRoom() {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.exitRoom()
                }

                2 -> {
                    mGamePlayFragment?.exitRoom()
                }

                else -> {}
            }
        }

    }

    private fun showPriceModificationPromptPopup(message: String) {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.showPriceModificationPromptPopup(message)
                }

                2 -> {
                    mGamePlayFragment?.showPriceModificationPromptPopup(message)
                }

                else -> {}
            }
        }
    }

    private fun updateLiveRoomInfo(name: String, liveInfo: LiveRoomInfo) {
        mLiveInfo?.let {
            when (it.gameProviderType) {
                1 -> {
                    mBaiShunGamePlayFragment?.updateLiveRoomInfo(name, liveInfo)
                }

                2 -> {
                    mGamePlayFragment?.updateLiveRoomInfo(name, liveInfo)
                }

                else -> {}
            }
        }

    }

    /**
     * =========================Im消息回调==================
     */
    override fun closeRoomMessage(da: SendLiveCloseMessage) {
        mOnSpectatorFragmentListener?.closeActivity(da)
    }

    override fun variableUpdate(variable: RoomVariable) {
        val liveInfo = mLiveInfo ?: return
        LiveUtils.fillLiveInfo(liveInfo, variable)

        SeatBeanUtil.getSeatId(variable.name)?.let {
            mBinding.partySeat.setUpdateDateSeat(it, liveInfo)
        }

        updateLiveRoomInfo(variable.name, liveInfo)

        when (variable.name) {
            "showGainCoins" -> {
                mBinding.contributionView.showGainCoins((liveInfo.showGainCoins?.formatNumberWithK()) ?: "0")
            }

            "banMessageUser" -> {
                upDataBanMessage(liveInfo)
            }

            "administrator" -> {
                upDataAdministrator(liveInfo)
            }
            "roomTheme" -> {
                setSkinUi()
            }
        }
    }

    override fun userCountChange(count: Int) {
    }

    override fun publicMessage(message: SendLiveMessage) {
        if (message.type in ImLiveManager.publicTypes && message.businessId == mLiveInfo?.liveId) {
            mBinding.vMessage.addMessage(message)
            if (message.type == LIVE_PUBLIC_SCREEN) {
                val ext = message.ext as? MessageUserExtBean
                val isGameMode = mGameMode
                val isUserMessage = ext?.user?.userId == UserManager.getUserId()
                if (ext?.type == 1) {
                    if (!isGameMode || isUserMessage) {
                        mBinding.barrageView.addMessage(message)
                    }
                }
            }
        }
        //其他消息处理
        when (message.type) {
            LIVE_SEND_GIFT, LUCKY_BACKPACK_GIFT -> {
                val ext = message.ext as MessageUserExtBean
                val payload = message.payload as InviteGiftPayloadBean

                if (!getGameIsPlaying()) {
                    mGiftGivingAnimationProxy.sendGiftEffect(
                        requireContext(),
                        message,
                        mBinding.partySeat.getSeatData()
                    )
                    mGiftProxy?.addAnimation(message)
                    payload.gift.animation?.let { mBinding.widgetGift.setGift(payload) }
                }

                val isWinning = payload.reward != null && payload.reward.times > 0
                if (isWinning && UserManager.getUserId() == ext.user.userId) {
                    if (message.type != LUCKY_BACKPACK_GIFT) {
                        GlobalDialogManager.showUserWinning(requireContext(), payload)
                    } else {
                        mGiftDialogProxy.apply { }
                        GlobalDialogManager.showBackPackUserWinning(requireContext(), payload)
                    }
                }
            }
            //警告消息
            LIVE_WARN_MESSAGE -> {
                mLivePublicProxy.onPublicMessage(message)
            }
            //邀请上座信息
            LIVE_INVITE_SITE -> {
                showInvitingSeatNoticePopup(message)
            }

            LIVE_KICK_ROOM -> {
                ToastGravity.showGravity(message.content)
                mOnSpectatorFragmentListener?.closeActivity()
            }

            //礼物列表消息
            LIVE_GIFT_LIST -> {
                val payload = message.payload as GiftListPayloadBean
                val orNull = payload.gifts.getOrNull(0)
                orNull?.let {
                    playAnim(listOf(inAlpha(mBinding.widgetLiveFollower)))
                    mBinding.widgetLiveFollower.setData(
                        payload,
                        mLiveInfo?.avatar,
                        mLiveInfo?.userId
                    )
                    mGiftJob = lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
                        delay(payload.duration * 1000)
                        withContext(CoroutineScopeManager.mainDispatcher) {
                            if (mBinding.widgetLiveFollower.isVisible) {
                                playAnim(listOf(outAlpha(mBinding.widgetLiveFollower)))
                            }
                        }
                    }
                }
            }
            //emoji消息
            LIVE_PARTY_EMOJI -> {
                mBinding.partySeat.showUserEmoji(message)
            }
            //价格变化
            LIVE_CHANGED_GAME_REWARD -> {
                showPriceModificationPromptPopup(message.content)
            }

            LIVE_RELOAD_GAME -> { //重新加载游戏
                reloadGame()
            }
            //神灯进度90%
            LIVE_MAGIC_LAMP_90 -> {
                mBinding.widgetRoomBanner.upDataMagicLamp()
            }
            //神灯开奖
            LIVE_MAGIC_LAMP_OPEN -> {
                val payload = message.payload as MagicLampCountDownBean
                mBinding.widgetRoomBanner.upDataMagicLamp()
                mBinding.widgetMagicLamp.addMagicLampPag(payload)
            }
            //新人免费礼物累计
            NEW_COUPLES_FREE_GIFTS -> {
                mBinding.bottom.inspectFreeGift()//检查是否累计免费礼物
            }
        }
    }

    override fun liveEvent(command: String, argument: DataArgument) {
        when (command) {
            SFSEvent.USER_ENTER_ROOM -> {
                val user = argument.getUser()
                //过滤自己和主播
                if (user == null
                    || user.name == UserManager.getUserId().toString()
                    || user.name == mLiveInfo?.liveId?.toString()
                ) {
                    return
                }

                argument.getUser()?.parseVariables<LiveEnterBean>()?.let {
                    mEntryScreenAnimationProxy.addEntryScreenOtherUser(it) {
                        mBinding.vEnter.addEnterBean(it)
                    }
                }
            }

            SFSEvent.USER_EXIT_ROOM -> {
                val user = argument.getUser()
                if (user == null || user.name == UserManager.getUserId().toString()) {
                    return
                }
                mEntryScreenAnimationProxy.removeEntryScreen(user.name.toLong())

            }
            //如果是加入则刷新直播间的信息
            SFSEvent.ROOM_JOIN -> {
                argument.getRoom()?.also { room ->
                    if (room.getRoomId().toString() == mAnchorId.toString()) {
                        room.variables.forEach {
                            variableUpdate(it)
                        }
                    }
                }
                SmartFoxManager.getLiveMyself()?.parseVariables<LiveEnterBean>()?.let {
                    mEntryScreenAnimationProxy.addEntryScreenMe(it)
                }

            }
        }
    }

    override fun floatingMessage(message: SendLiveFloatingMessage) {
        mBinding.widgetFloat.addFloatView(message)
    }

    /**
     * =========================Im消息回调END==================
     */

    private fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBarMarginTop(mBinding.heardLl)
            .init()

        NavigationBarUtils.setNavigationHeight(mBinding.bottom)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initImmersionBar()
        mAnchorId = arguments?.getLong("anchorId", -1L) ?: -1
        mIsMatchCome = arguments?.getBoolean(LiveConst.Params.IS_MATCH_COME_GAME)
        mSoundStatus = arguments?.getBoolean(LiveConst.Params.SOUND_STATUS)

        mBinding.apply {
            bottom.initialize(mBottomBuilder, mViewModel)
            contributionView.showGainCoins(mLiveInfo?.showGainCoins?.formatNumberWithK() ?: "0")
        }

        initObserve()
        initListener()
        if (!mIsInitLiveInfo) {
            loading()
        }
        if (resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL) {
            mBinding.close.scaleX = -1f
            mBinding.close.setPadding(10.dp, 0, 0, 0)
        }
        mViewModel.openClearTimeJob()
        mViewModel.getBackGiftRed()
        mBinding.actMarquee.getActivitiesScroll(mViewModel, mAnchorId)
    }

    private fun initObserve() {
        mViewModel.clearTimeLiveData.observe(this) { _ ->
            mGiftGivingAnimationProxy.clearOverTimeQueue()
        }
        //关注主播
        mViewModel.liveFollowLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(string.follower_succeed)
                clearFollower()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //关注房间
        mViewModel.followRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(string.follower_succeed)
                mBinding.vHeader.updateFollowStatus(true)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //获取礼物飘屏用户信息
        mViewModel.giftInfoLiveData.observe(this) { resultState ->
            parseState(resultState, { user ->
                when (user.live?.liveType) {
                    LiveConst.Type.PARTY_LIVE -> {
                        Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                            .withInt(LiveConst.Params.LIVETYPE, LiveConst.Type.PARTY_LIVE)
                            .withLong(LiveConst.Params.ANCHORID, user.userId)
                            .navigation(requireContext())
                    }

                    LiveConst.Type.VIDEO_PARTY -> {
                        Router.instance.setPath(RoutePath.PARTY_SPECTATOR_ACTIVITY)
                            .withInt(LiveConst.Params.LIVETYPE, LiveConst.Type.VIDEO_PARTY)
                            .withLong(LiveConst.Params.ANCHORID, user.userId)
                            .navigation(requireContext())
                    }

                    LiveConst.Type.PARTY_GAME_LIVE -> {
                        nextData(user.toDisplayUserBean())
                    }

                    else -> {
                        if (user.live?.living == true) {
                            LiveUtils.toSpectator(user).navigation(requireActivity())
                            mOnSpectatorFragmentListener?.closeActivity()
                        }
                    }
                }
            })
        }

        //获取房间关注
        mViewModel.isFollowRoomLiveData.observe(this) { resultState ->
            parseState(resultState, { follow ->
                mBinding.vHeader.setUserFollower(follow)
            })
        }
        //获取游戏列表
        mViewModel.gameLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.bottom.showGameButton(it.isNotEmpty())
                GameUtils.setLiveCacheGameList(it)
                mLiveInfo?.liveId?.let { liveId ->
                    mViewModel.gameRank(liveId)
                }
            })
        }
        //直播获取顶部消费列表
        mViewModel.liveConsumeLiveData.observe(this) { (liveId, it) ->
            if (mLiveInfo?.liveId == liveId) {
                mBinding.vHeader.updateConsumeList(it)
                mBinding.widgetRoomBanner.upDataMagicLamp()
            }
        }
        //活动滚动信息刷新
        mViewModel.activitiesScrollLiveData.observe(this) {
            mLiveInfo?.let { info ->
                mBinding.actMarquee.getActivitiesScroll(mViewModel, info.userId)
            }
        }
        //点击隐藏edit
        ViewUtils.registerTouchDown(mBinding.widgetGift) {
            mEditView?.hideKeyboard()
        }
        //获取emoji列表
        mViewModel.mEmojiListLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mEmojiList = it
                showInteractionEmojiPopup()
            })
        }
        //路由监听
        RouterControlManager.observeListener(this) { key, ext ->
            if (isVisibleToUser) {
                withLoaded {
                    when (key) {
                        RouterControlManager.ROUTER_ROOMGAME -> { //打开幸运游戏列表
                            val gameId = ext["gameId"]?.toLongOrNull()
                            if (gameId == null) {
                                showGameList()
                            } else {
                                val gameVo = GameUtils.getLiveCacheGameList()
                                    ?.asSequence()
                                    ?.flatMap { it.list.asSequence() }
                                    ?.find { it.gameID == gameId }
                                if (gameVo != null) {
                                    val roomId = mLiveInfo?.userId.toString()
                                    GameUtils.showGameFragment(requireContext(), gameVo, roomId = roomId)
                                } else {
                                    showGameList()
                                }
                            }
                        }

                        RouterControlManager.ROUTER_GIFT -> { //礼物盘拉起
                            val giftType = ext["giftType"]?.toIntOrNull()
                            mGiftDialogProxy?.showGiftPopup(
                                seatList = mBinding.partySeat.getSeatData(),
                                giftType = giftType
                            )
                        }

                        RouterControlManager.ROUTER_UP_MIC -> { //上麦
                            mBinding.partySeat.getNoHavaSeat()?.let { showSitePop(it) }
                        }

                        RouterControlManager.ROUTER_PARTYGAMEUP -> { //上游戏位
                            mGamePlayFragment?.siteUpDown(true)
                            mBaiShunGamePlayFragment?.siteUpDown(true)
                        }
                    }
                }

            }
        }
        //房间关闭后游戏结算推送
        ImNoticeManager.observeGameResult(this) {
            if (roomClose) {
                gameResult(it)
            }
        }
        mViewModel.mBackGiftRedData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.bottom.setBackPackRed(if (it) View.VISIBLE else View.GONE)
            })
        }
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId) {
                            mOnSpectatorFragmentListener?.closeActivity()
                        }
                } else {
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(requireActivity())
                }
            })
        }
        TaskRedProxy.observe(this, object : TaskRedListener {
            override fun updateRed(isRed: Boolean) {
                mBinding.bottom.setSettingRed(if (isRed) View.VISIBLE else View.GONE)
            }
        })
        mViewModel.mLampLotteryLiveData.observe(this) { resultState ->
            parseState(resultState, {
                MagicLampWinRewardPopup.show(requireContext(), it)
            }) {
                ToastGravity.showGravity(it.errorMsg)
            }
        }
        mBinding.widgetMagicLamp.openMagicLampCallBack {
            mLiveInfo?.userId?.let { userId ->
                mViewModel.lampLottery(userId, it.index.toLong())
            }
        }
        //免费礼物
        mViewModel.mSendFreeGiftLiveData.observe(this) {
            mBinding.bottom.inspectFreeGift()
        }
        //更新弹幕信息
        mViewModel.barrageNumberLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mEditView?.upBarrage(it)
            })
        }
    }

    private fun initListener() {
        mBinding.apply {
            /**
             * 观众点击了，吊起礼物盘
             */
            actMarquee.setGiftIdBackListener {
                mGiftDialogProxy?.showGiftPopup(mLiveInfo?.toUserBasic(), it)
            }
            //直播间飘屏被点击
            widgetFloat.setOnSingleClickListener { data ->
                when (data.type) {
                    LiveFloatView.GIFT -> { //礼物飘屏
                        //没在游戏位且没在游戏中才可以跳转
                        if (!mInSeat && !mGameMode) {
                            val seatBean =
                                mBinding.partySeat.getSeatBeanByUserId(UserManager.getUserId())
                            if (seatBean != null) {
                                ToastGravity.showGravity(string.sure_exit_party_tips)
                                return@setOnSingleClickListener
                            }
                            RouterUtils.getAnchorId(data.router)?.let { id ->
                                if (mAnchorId != id) {
                                    mViewModel.getGiftInfoUser(id)
                                }
                            }
                        }
                    }

                    LiveFloatView.GAME -> { //游戏中奖
                        GameUtils.showAndCheckGameFragment(
                            requireContext(),
                            mLiveInfo?.userId,
                            data.payload
                        )
                    }

                    LiveFloatView.ROOM -> { //开房通知
                        data.router?.let {
                            val pathUrl = RouterUtils.routerGetPath(it)
                            RouterUtils.killTopActivity(it, pathUrl)
                        }
                    }

                    LiveFloatView.GENERAL -> { //通用
                        data.router?.let {
                            RouterUtils.routerGoto(it)
                        }
                    }
                }
            }
            //直播间用户列表
            vHeader.setOnConsumeItemClickListener { _, item ->
                if (item.userId == UserManager.getUserId()) {
                    showPartyUserProfilePopup(item.userId, true)
                } else {
                    mGiftDialogProxy?.showGiftPopup(
                        UserBasicVo(
                            userId = item.userId,
                            avatar = item.avatar,
                            avatarFrame = item.avatarFrame,
                            userNumber = 0,
                            sex = AppConst.UserSex.NONE,
                            nickname = "",
                            createTime = 0,
                            richs = 0,
                            charms = 0
                        )
                    )
                }
            }
            //点击主播头像
            vHeader.setOnAvatarClientListener {
                showRoomInfoPopup()
            }
            //点击关注
            vHeader.setOnFollowerClickListener {
                mLiveInfo?.userId?.also { userId ->
                    mViewModel.addFollowRoom(userId)
                }
            }
            //点击在线人数
            vHeader.setOnOnlineClickListener {
                mLiveInfo?.let {
                    GlobalPopupManager.showOnRoomUser(
                        requireContext(), this@PartyGameSpectatorFragment, mViewModel,
                        it.liveId, it.userId, LiveConst.Type.PARTY_GAME_LIVE,
                        mAdministrators,
                        onHeadClickListener = { userId ->
                            showPartyUserProfilePopup(userId, true)
                        }, onSendGiftSomeOneCallback = { userBase ->
                            if (userBase == null) {
                                mGiftDialogProxy?.showGiftPopup(seatList = mBinding.partySeat.getSeatData())
                            } else {
                                if (userBase.userId != UserManager.getUserId()) {
                                    mGiftDialogProxy?.showGiftPopup(userBase)
                                }

                            }
                        })
                }
            }
            sourceCl.setOnSingleClickListener {
                vMessage.closeMessage()
            }
            //赠送礼物
            vMessage.mBinding.baseMessage.setOnSendGiftListener {
                mViewModel.sendGift(requireContext(), it, LiveConst.SendGift.publicGift)
            }
            //赠送关注礼物
            vMessage.mBinding.baseMessage.setOnSendFollowerListener {
                mViewModel.sendGift(requireContext(), it, LiveConst.SendGift.followerGift)
//                vHeader.updateFollowStatus(true)
            }
            //控制键盘
            vMessage.setOnClick {
                mEditView?.showKeyboard()
            }
            //点击屏幕中间关注礼物
            widgetLiveFollower.setOnCallSendGiftList { gift, type ->
                sendGift(gift, type)
            }
            /**
             * 上座信息
             */
            vMessage.mBinding.baseMessage.setOnSendUpSeatListener {
                upSeat(false, null)
            }
            //公屏举报
            vMessage.mBinding.baseMessage.setOnReportListener {
                if (it.ext is MessageUserExtBean) {
                    GlobalPopupManager.showReport(
                        requireContext(), it.ext.user.nickname,
                        mViewModel, it.ext.user.userId, mLiveInfo?.liveId
                    )
                }
            }
            //显示头像
            vMessage.mBinding.baseMessage.setOnUserProfileClickListener {
                showPartyUserProfilePopup(it, true)
            }
            close.setOnSingleClickListener {
                if (!onBackPressed()) {
                    mOnSpectatorFragmentListener?.closeActivity()
                }

            }
            /**
             * 座位回调
             */
            partySeat.setPartySeatListener(object : PartySeatListener {
                /**
                 * 被点击
                 */
                override fun clickItem(index: Int, seatBean: SeatBean) {
                    //有人
                    if (seatBean.userBasicVo != null) {
                        seatBean.userBasicVo?.userId?.let {
                            if (it == UserManager.getUserId()) {
                                showPartyUserProfilePopup(it, false, seatBean)
                            } else {
                                mGiftDialogProxy?.showGiftPopup(seatBean.userBasicVo)
                            }
                        }
                    } else {
                        val find = mAdministrators.find { it == UserManager.getUserId() }
                        if (find != null) {
                            showSeatPopup(seatBean)
                        } else {
                            showSitePop(seatBean)
                        }
                    }
                }

                override fun updateOneSelfSeat(seatBean: SeatBean?) {
                    if (!mInSeat && seatBean == null) {
                        mOnSpectatorFragmentListener?.prohibitSliding(false, showTips = true)
                    } else {
                        mOnSpectatorFragmentListener?.prohibitSliding(true, showTips = true)
                    }
                    if (seatBean == null || seatBean.siteMicStatus != 1) {
                        MediaProxy.closeMusic()
                    }
                    mBinding.bottom.apply {
                        if (seatBean == null) {
                            showMikeButton(false)
                            showEmojiButton(false)
                        } else {
                            setMikeState(seatBean.siteMicStatus ?: 1)
                            showMikeButton(true)
                            showEmojiButton(true)
                        }
                    }

                }

                override fun soundLevelUpdate(seatId: Int, soundLevel: Float) {
                    mLiveInfo?.let {
                        mViewModel.taskMicReport(it.liveId.toString(), seatId.toLong(), soundLevel.toString())
                    }

                }

            })
            /**
             * 点击贡献榜
             */
            contributionView.setOnSingleClickListener {
                ContributionListPopup.showPop(
                    requireContext(),
                    this@PartyGameSpectatorFragment,
                    mViewModel,
                    mAnchorId
                ) {
                }
            }
            widgetRoomBanner.setOnTouchCallback {
                if (!it) {
                    mOnSpectatorFragmentListener?.onBannerTouch(false)
                } else {
                    mOnSpectatorFragmentListener?.onBannerTouch(PartyUserStateUtil.inTheGame)
                }
            }
            widgetRoomBanner.setMagicLampListener {
                mLiveInfo?.let { info ->
                    MagicLampPopup.show(this@PartyGameSpectatorFragment, mViewModel, info.userId, false) {
                        mGiftDialogProxy?.showGiftPopup(seatList = mBinding.partySeat.getSeatData())
                    }
                }

            }
            barrageView.addReportCallBack {
                GlobalPopupManager.showReport(
                    requireContext(),
                    it.nickname,
                    mViewModel,
                    it.userId,
                    it.userId
                )
            }
        }
    }

    private fun clearFollower() {
        mBinding.vMessage.mBinding.baseMessage.clearFollower()
//        mBinding.vHeader.updateFollowStatus(true)
    }

    /**
     * 显示房间管理RoomManagement
     */
    private fun showRoomManagementPopup() {
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(false)
            .moveUpToKeyboard(false)
            .isDestroyOnDismiss(true)
            .asCustom(
                mLiveInfo?.let {
                    RoomManagementPopup(requireContext(), false, 1, false, false,
                        it, mViewModel, mBinding.widgetGift.getIsOpenGift(), mBinding.widgetGift.getIsOpenSound(),
                        onOpenGiftAnimation = {
                            mBinding.widgetGift.setIsOpenGiftAnimation(it)
                            mBinding.widgetMagicLamp.setIsOpenGiftAnimation(it)
                        }, onOpenGiftSound = {
                            mBinding.widgetGift.setIsOpenSound(it)
                        }, music = {
                            MusicPopup.show(this@PartyGameSpectatorFragment) {
                                upSeat(false, null)
                            }
                        }, onInvitationFriend = {
                            mLiveInfo?.liveId?.let { liveId ->
                                val fragmentManager = childFragmentManager
                                RoomInvitationFragmentDialog().apply {
                                    arguments = bundleOf("liveId" to liveId)
                                }.show(
                                    fragmentManager,
                                    "RoomInvitationFragmentDialog"
                                )
                            }
                        })
                }
            )
            .show()
    }

    //赠送关注礼物
    private fun sendGift(gift: GiftBean, type: Int) {
        val userId = mLiveInfo?.userId
        val liveId = mLiveInfo?.liveId
        if (userId != null && liveId != null) {
            val sendGiftBean = SendGiftBean(
                recipient = userId,
                giftId = gift.id,
                count = 1,
                sourceType = AppConst.GiftComming.CALL,
                objectId = liveId,
                payload = gift.payload
            )
            mViewModel.sendGift(requireContext(), sendGiftBean, type)

            if (type == LiveConst.SendGift.followerGift) {
//                mBinding.vHeader.updateFollowStatus(true)
            }
            if (mBinding.widgetLiveFollower.isVisible) {
                mGiftJob?.cancel()
                playAnim(listOf(outAlpha(mBinding.widgetLiveFollower)))
            }
        }
    }

    /**
     * 加入直播间成功
     */
    override fun initLiveInfo(data: LiveInitInfo, password: String?) {
        mIsInitLiveInfo = true
        withLoaded {
            super.initLiveInfo(data, password)
            mGiftGivingAnimationProxy.initSeatViewAddr(
                mBinding.gifta, 0, 0, Pair("1", mBinding.partySeat.mBinding.seat1),
                Pair("2", mBinding.partySeat.mBinding.seat2),
                Pair("3", mBinding.partySeat.mBinding.seat3),
                Pair("4", mBinding.partySeat.mBinding.seat4),
                Pair("5", mBinding.partySeat.mBinding.seat5),
                Pair("6", mBinding.partySeat.mBinding.seat6),
                Pair("7", mBinding.partySeat.mBinding.seat7),
                Pair("8", mBinding.partySeat.mBinding.seat8),
            )

            mBinding.sourceCl.visibility = View.VISIBLE

            Glide.with(this)
                .load(ImageUtils.imgPath(data.info.background))
                .placeholder(R.drawable.party_bg)
                .centerCrop()
                .into(mBinding.gameBg)


            mViewModel.getFollowRoomUser(mAnchorId)
            mViewModel.getGameList(data.info.liveId)
            mViewModel.launchConsumeUser(data.info.liveId) //定时5秒请求一次  顶部消费列表

            //发送公屏消息
            mEditView?.setOnSendPartyMessageListener(object : OnSendPartyMessageListener {
                override fun onSendPublicMessage(message: LivePublicScreenMessage) {
                    mViewModel.sendPublicMessage(message)
                }

                override fun onBarrageWhat() {
                    VipBarrageWhatPopup.showPop(requireContext(), true) {
                        Router.instance.setPath(RoutePath.VIP_CENTER_ACTIVITY)
                            .withInt("page", 0)
                            .withInt("level", 6)
                            .navigation(requireContext())
                    }
                }
            })
            val variable = data.info
            mLiveInfo = variable
            initGameFragment(variable)

            mLiveInfo?.userId?.let { mBinding.partySeat.setInitJoinData(variable, it) }
            mBinding.apply {
                vHeader.initData(pageType, variable, data.userCount)
                vMessage.initData(pageType, variable)
                mEditView?.initData(variable)
                widgetRoomBanner.initBannerData(lifecycle, mViewModel, variable.liveId, variable.userId)
                bottom.inspectFreeGift()//检查是否累计免费礼物
                CommonCache.getMagicLampList().forEach { widgetMagicLamp.addMagicLampPag(it) }
            }
            mGiftProxy = GiftAnimationProxy(this, requireContext(), mBinding.llGift, variable.nickname)
                .apply {
                    //礼物队列点击头像
                    setOnHeadOnClickListener {
                        showPartyUserProfilePopup(it, true)
                    }
                }
            mLiveInfo?.let { upDataAdministrator(it) }
            mLiveInfo?.let { upDataBanMessage(it) }
            loadGame(variable)
            setSkinUi()
        }
    }

    private fun initGameFragment(liveInfo: LiveRoomInfo) {
        val uuid = this.arguments?.getString("fragmentPageId") ?: CommonUtils.uuid()
        when (liveInfo.gameProviderType) {
            1 -> {
                mBaiShunGamePlayFragment = childFragmentManager.attachFragmentByTag(
                    R.id.fragment_game,
                    uuid
                ) {
                    BaiShunGamePlayFragment().apply {
                        arguments = bundleOf(
                            LiveConst.Params.IS_ANCHORID to false,
                            LiveConst.Params.IS_MATCH_COME_GAME to mIsMatchCome,
                            LiveConst.Params.SOUND_STATUS to mSoundStatus
                        )
                    }
                }.apply {
                    setGamePlayListener(this@PartyGameSpectatorFragment)
                    setOnClickSendGiftCallback {
                        showGiftDialog()
                    }
                }
            }

            2 -> {
                mGamePlayFragment = childFragmentManager.attachFragmentByTag(
                    R.id.fragment_game,
                    uuid
                ) {
                    GamePlayFragment().apply {
                        arguments = bundleOf(
                            LiveConst.Params.IS_ANCHORID to false,
                            LiveConst.Params.IS_MATCH_COME_GAME to mIsMatchCome,
                            LiveConst.Params.SOUND_STATUS to mSoundStatus
                        )
                    }
                }.apply {
                    setGamePlayListener(this@PartyGameSpectatorFragment)
                    setOnClickSendGiftCallback {
                        showGiftDialog()
                    }
                }
            }
        }

    }

    /**
     * 退出房间
     */
    override fun exitRoom() {
        if (!isCreated()) {
            return
        }
        super.exitRoom()
        exitFragmetRoom()
        LiveEngineManage.getGameEngineHandler()?.unloadGame()
        mBinding.sourceCl.visibility = View.INVISIBLE
        stopJob()
        mViewModel.stopConsumeJob()
        mViewModel.cancelGameRankJob()
        mEditView?.reset()
        mBinding.apply {
            vHeader.reset()
            partySeat.reset()
            vMessage.reset()
            mGiftProxy?.reset()
            mGiftDialogProxy?.reset()
            mEntryScreenAnimationProxy.reset()
            actMarquee.reset()
        }
    }

    /**
     * 获取这个房间上座信息
     */
    override fun getIsRoomSeat(): Boolean {
        return mBinding.partySeat.getMeSeatBean() != null || mInSeat
    }

    override fun getIsGameMode(): Boolean {
        return mGameMode
    }

    /**
     * 显示房间信息
     */
    private fun showRoomInfoPopup() {
        mLiveInfo?.let {
            RoomInfoSpectatorPopup.show(
                this,
                it.liveId,
                it.userId,
                it.roomId ?: "",
                mLiveInfo?.vipLevel,
                mLiveInfo?.roomTheme,
                { userId ->
                    if (mLiveInfo?.userId == userId) { //点击房主
                        mGiftDialogProxy?.showGiftPopup(mLiveInfo?.toUserBasic())
                    } else {
                        showPartyUserProfilePopup(userId, true)
                    }
                }) {
                mBinding.vHeader.updateFollowStatus(it)
            }
        }
    }

    /**
     * 显示资料卡片
     * search 是否查找座位上的人信息
     */
    private fun showPartyUserProfilePopup(
        userId: Long,
        search: Boolean = false,
        seatBean: SeatBean? = null,
    ) {
        val mutableSeatBean =
            seatBean ?: if (search) mBinding.partySeat.getSeatBeanByUserId(userId) else null
        GlobalPopupManager.showPartyUserProfilePopup(
            requireContext(), this, mViewModel,
            userId, UserConst.From.LIVE,
            mLiveInfo?.liveId, mLiveInfo?.userId,
            mutableSeatBean,
            onLeaveSeatClickListener = {
                mViewModel.liveSiteDown(mAnchorId)
            }, onGiftClickListener = {
                //点击送礼
                mGiftDialogProxy?.showGiftPopup(it.toUserBasicVo())
            }, onMessageClickListener = {
                showChatMessage(it.toUserBasicVo())
            }, onSelectMoreCardListener = {
                showSelectMoreCard(it)
            })
    }

    private fun showSelectMoreCard(infoUserResp: InfoOtherResp) {
        val mutableSeatBean = mBinding.partySeat.getSeatBeanByUserId(infoUserResp.userId)
        GlobalPopupManager.showSelectMoreCard(
            requireContext(), this, mViewModel,
            infoUserResp, mutableSeatBean, mBanMessageUser,
            mAdministrators,
            mLiveInfo?.liveId,
            mLiveInfo?.userId,
            false,
            onInviteOrKickSiteListener = {
                if (it) {
                    mLiveInfo?.liveId?.let { it1 -> mViewModel.partyInviteSite(infoUserResp.userId, null, it1) }
                } else {
                    //踢下座位
                    mLiveInfo?.userId?.let { it1 -> mViewModel.siteKick(infoUserResp.userId, it1) }
                }
            }, onKickRoomListener = {
                //踢出房间
                mLiveInfo?.userId?.let { mViewModel.kickUser(infoUserResp.userId, it, mLiveInfo?.roomId) }
            }, onAtClickListener = {
                mEditView?.atUser(infoUserResp.userId, infoUserResp.nickname)
            }
        )
    }

    private fun showGameList() {
        val roomId = (mLiveInfo?.userId ?: "").toString()
        GameListPopup.show(requireContext(), GameUtils.getLiveCacheGameList(), roomId)
    }

    /**
     * 显示Emoji管理
     */
    private fun showInteractionEmojiPopup() {
        if (mEmojiList == null) {
            mViewModel.emojiList()
            return
        }
        mEmojiList?.let {
            XPopupUtils.showViewPopup(
                InteractionEmojiPopup(requireContext(), it, mViewModel, {
                    mLiveInfo?.liveId?.let { it1 -> mViewModel.sendEmoji(it.id, it1) }
                }) {
                    mEmojiList = null
                }
            )
        }
    }

    /**
     * 邀请上座Pop
     */
    private fun showInvitingSeatNoticePopup(liveMessage: SendLiveMessage) {
        InvitingSeatNoticePopup.show(
            requireContext(),
            liveMessage, {
                mLiveInfo?.liveId?.let {
                    mViewModel.partyRejectSite(it)
                }
            }
        ) {
            SnackbarUtils.dismiss()
            upSeat(true, it)
        }
    }

    /**
     * 显示座位管理
     */
    private fun showSeatPopup(seatBean: SeatBean) {
        val userId = mLiveInfo?.userId ?: return
        val liveId = mLiveInfo?.liveId ?: return
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(
                SeatSettingPopup(
                    requireContext(), seatBean, mViewModel, userId, liveId
                ) {
                    showSitePop(seatBean)
                }
            )
            .show()
    }

    /**
     * 上麦
     */
    private fun showSitePop(seatBean: SeatBean) {
        //麦位被锁不响应
        if (seatBean.siteLock != true) {
            StartLiveProxy.permissionAudio(requireContext(), {
                upSeat(false, seatBean.seatId)
            })
        }
    }

    private fun upSeat(isInvite: Boolean, seatId: Int?) {
        StartLiveProxy.permissionAudio(requireContext(), {
            mViewModel.liveSiteUp(mAnchorId, isInvite, seatId)
        })
    }

    private var mInspectPublishJob: Job? = null

    /**
     * 延迟一秒检查推流情况,等打电话界面关闭推流再打开
     */
    private fun inspectPublishStream() {
        withLoaded {
            stopJob()
            mInspectPublishJob = mViewModel.viewModelScope.launch {
                try {
                    delay(1000)
                    mBinding.partySeat.inspectMaishangZego()
                } finally {
                    if (mInspectPublishJob == coroutineContext[Job]) {
                        mInspectPublishJob = null
                    }
                }
            }
        }
    }

    private fun stopJob() {
        mInspectPublishJob?.cancel()
        mInspectPublishJob = null
    }

    override fun getZegoGameEngineHandler(): IZegoGameEngineHandler? {
        return mGamePlayFragment
    }

    //判断当时fragment是展示的还是隐藏的
    private var isVisibleToUser = false
    override fun onResume() {
        super.onResume()
        mBinding.partySeat.onResume()
        isVisibleToUser = true
        withLoaded {
            inspectPublishStream()
        }
    }

    override fun onPause() {
        super.onPause()
        isVisibleToUser = false
//        mBinding.partySeat.onPause()
        stopJob()
    }

    override fun onDestroyView() {
        exitRoom()
        mBinding.partySeat.destroyView()
        LiveEngineManage.getGameEngineHandler()?.unloadGame()
        mViewModel.stopClearTimeJob()
        super.onDestroyView()
    }

    /**
     * 展示消息列表
     */
    private fun showChatMessage(userBase: UserBasicVo? = null) {
        if (userBase != null) {
            childFragmentManager.showNewDialogFragment(
                MessageSingleDialogFragment(
                    userBase.userId,
                    userBase.avatar,
                    userBase.avatarFrame,
                    userBase.chatBubble,
                    nestedPage = false,
                    singlePage = true
                ), MessageSessionFragment.FRAGMENT_TAG
            )
        } else {
            mSessionFragment.show(
                childFragmentManager,
                MessageSessionDialogFragment.FRAGMENT_TAG
            )
        }
    }

    /**
     * 更新禁止发言用户
     */
    private fun upDataBanMessage(liveInfo: LiveRoomInfo) {
        mBanMessageUser.clear()
        liveInfo.banMessageUser?.let { banMessageUserJson ->
            val data: List<Long>? = JsonUtils.fromJson(banMessageUserJson)
            data?.let {
                mBanMessageUser.addAll(it)
            }
        }
    }

    /**
     * 更新管理员
     */
    private fun upDataAdministrator(liveInfo: LiveRoomInfo) {
        mAdministrators.clear()
        liveInfo.administrator?.let {
            val data: List<Long>? = JsonUtils.fromJson(it)
            if (data?.isNotEmpty() != null) {
                mLiveInfo?.userId?.let { it1 -> mBinding.partySeat.upDataUserPosition(data, it1) }
                mAdministrators.addAll(data)
            }
        }
    }

    override fun setMessageHeight(h: Int) {
        mBinding.vMessage.setMessageHeight(h)
    }

    /**
     * 游戏回调
     */
    override fun gamePlayerStart() {
        PartyUserStateUtil.inTheGame = true
        mBinding.widgetGift.visibility = View.GONE
        ViewUtils.setMargin(mBinding.llGift, 0, 0, 0, 100.dp)
        mOnSpectatorFragmentListener?.gameMode(true)
        mGameMode = true
    }

    override fun gamePlayerStop() {
        PartyUserStateUtil.inTheGame = false
        mBinding.widgetGift.visibility = View.VISIBLE
        ViewUtils.setMargin(mBinding.llGift, 0, 0, 0, 12.dp)
        mOnSpectatorFragmentListener?.gameMode(false)
        mGameMode = false
    }

    override fun gamePlayerInSeat(inSeat: Boolean) {
        PartyUserStateUtil.inTheGameSeat = inSeat
        mInSeat = inSeat
        if (!inSeat && !getIsRoomSeat()) {
            mOnSpectatorFragmentListener?.prohibitSliding(false, showTips = true)
        } else {
            mOnSpectatorFragmentListener?.prohibitSliding(true, showTips = true)
        }

    }

    override fun gameSeatClick(userId: Long) {
        showPartyUserProfilePopup(userId, false)
    }

    /**
     * 更新皮肤
     */
    private fun setSkinUi() {
        val themeData = AppConfigManager.getUserTheme(mLiveInfo?.roomTheme)
        mBinding.partySeat.setTheme(themeData)
        mBinding.vHeader.setTheme(themeData)
        mBinding.bottom.setTheme(themeData)
    }

    companion object {

        private const val pageType = LiveConst.Page.LIVE_SPECTATOR
    }
}